//
//  DMInterstitialSceneManager.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/15.
//

#import "DMInterstitialSceneManager.h"
#import "DMInterstitialManager.h"
#import "DualMediationMAXInterstitialManager.h"
#import "../../Utils/Logger/IMLogUtils.h"

@interface DMInterstitialSceneManager ()

@property (nonatomic, strong) NSTimer *playTimeTimer;
@property (nonatomic, strong) NSTimer *levelWaitTimer;
@property (nonatomic, assign) NSTimeInterval playTimeStartTime;
@property (nonatomic, assign) NSTimeInterval levelWaitStartTime;
@property (nonatomic, assign) BOOL isTimersPaused;

@end

@implementation DMInterstitialSceneManager

static DMInterstitialSceneManager *_sharedManager = nil;

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });
    return _sharedManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _sceneManagerEnabled = YES;
        _playTimeInterval = 300.0; // 5分钟
        _levelWaitInterval = 180.0; // 3分钟
        _isTimersPaused = NO;
        
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 场景管理器初始化完成"];
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 游戏时长间隔: %.0f秒", _playTimeInterval];
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 关卡等待间隔: %.0f秒", _levelWaitInterval];
    }
    return self;
}

- (void)dealloc {
    [self stopSceneManagement];
}

#pragma mark - Public Methods

- (void)startSceneManagement {
    if (!self.sceneManagerEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 场景管理器已禁用，跳过启动"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🚀 开始场景管理"];
    
    [self stopSceneManagement]; // 先停止现有的定时器
    
    // 启动游戏时长定时器
    [self startPlayTimeTimer];
    
    // 启动关卡等待定时器
    [self startLevelWaitTimer];
}

- (void)stopSceneManagement {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🛑 停止场景管理"];
    
    [self invalidatePlayTimeTimer];
    [self invalidateLevelWaitTimer];
}

- (void)triggerPlayTimeScene {
    if (!self.sceneManagerEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 场景管理器已禁用，跳过游戏时长场景触发"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ⏰ 触发游戏时长场景: %@", SCENE_INTER_PLAY_TIME];
    
    // 优先使用IronSource管理器
    if (self.ironSourceManager) {
        [self.ironSourceManager showInterAd:SCENE_INTER_PLAY_TIME];
    } else if (self.maxManager) {
        [self.maxManager showInterAd:SCENE_INTER_PLAY_TIME];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [SceneManager] ❌ 没有可用的插屏广告管理器"];
    }
    
    // 重置定时器
    [self resetPlayTimeTimer];
}

- (void)triggerLevelWaitScene {
    if (!self.sceneManagerEnabled) {
        [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 场景管理器已禁用，跳过关卡等待场景触发"];
        return;
    }
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ⏰ 触发关卡等待场景: %@", SCENE_INTER_LEVEL_WAIT];
    
    // 优先使用IronSource管理器
    if (self.ironSourceManager) {
        [self.ironSourceManager showInterAd:SCENE_INTER_LEVEL_WAIT];
    } else if (self.maxManager) {
        [self.maxManager showInterAd:SCENE_INTER_LEVEL_WAIT];
    } else {
        [IMLogUtils warning:IMLogTagAd format:@"📱 [SceneManager] ❌ 没有可用的插屏广告管理器"];
    }
    
    // 重置定时器
    [self resetLevelWaitTimer];
}

- (void)resetPlayTimeTimer {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🔄 重置游戏时长定时器"];
    [self invalidatePlayTimeTimer];
    if (self.sceneManagerEnabled && !self.isTimersPaused) {
        [self startPlayTimeTimer];
    }
}

- (void)resetLevelWaitTimer {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🔄 重置关卡等待定时器"];
    [self invalidateLevelWaitTimer];
    if (self.sceneManagerEnabled && !self.isTimersPaused) {
        [self startLevelWaitTimer];
    }
}

- (void)pauseAllTimers {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ⏸️ 暂停所有定时器"];
    self.isTimersPaused = YES;
    [self invalidatePlayTimeTimer];
    [self invalidateLevelWaitTimer];
}

- (void)resumeAllTimers {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ▶️ 恢复所有定时器"];
    self.isTimersPaused = NO;
    if (self.sceneManagerEnabled) {
        [self startPlayTimeTimer];
        [self startLevelWaitTimer];
    }
}

#pragma mark - Private Methods

- (void)startPlayTimeTimer {
    if (self.playTimeTimer) {
        [self.playTimeTimer invalidate];
    }
    
    self.playTimeStartTime = [[NSDate date] timeIntervalSince1970];
    self.playTimeTimer = [NSTimer scheduledTimerWithTimeInterval:self.playTimeInterval
                                                          target:self
                                                        selector:@selector(playTimeTimerFired:)
                                                        userInfo:nil
                                                         repeats:NO];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ⏱️ 游戏时长定时器已启动，%.0f秒后触发", self.playTimeInterval];
}

- (void)startLevelWaitTimer {
    if (self.levelWaitTimer) {
        [self.levelWaitTimer invalidate];
    }
    
    self.levelWaitStartTime = [[NSDate date] timeIntervalSince1970];
    self.levelWaitTimer = [NSTimer scheduledTimerWithTimeInterval:self.levelWaitInterval
                                                           target:self
                                                         selector:@selector(levelWaitTimerFired:)
                                                         userInfo:nil
                                                          repeats:NO];
    
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] ⏱️ 关卡等待定时器已启动，%.0f秒后触发", self.levelWaitInterval];
}

- (void)invalidatePlayTimeTimer {
    if (self.playTimeTimer) {
        [self.playTimeTimer invalidate];
        self.playTimeTimer = nil;
        [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneManager] 游戏时长定时器已停止"];
    }
}

- (void)invalidateLevelWaitTimer {
    if (self.levelWaitTimer) {
        [self.levelWaitTimer invalidate];
        self.levelWaitTimer = nil;
        [IMLogUtils debug:IMLogTagAd format:@"📱 [SceneManager] 关卡等待定时器已停止"];
    }
}

#pragma mark - Timer Callbacks

- (void)playTimeTimerFired:(NSTimer *)timer {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🔔 游戏时长定时器触发"];
    [self triggerPlayTimeScene];
}

- (void)levelWaitTimerFired:(NSTimer *)timer {
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 🔔 关卡等待定时器触发"];
    [self triggerLevelWaitScene];
}

#pragma mark - Setters

- (void)setSceneManagerEnabled:(BOOL)sceneManagerEnabled {
    _sceneManagerEnabled = sceneManagerEnabled;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 场景管理器状态: %@", sceneManagerEnabled ? @"启用" : @"禁用"];
    
    if (sceneManagerEnabled) {
        [self startSceneManagement];
    } else {
        [self stopSceneManagement];
    }
}

- (void)setPlayTimeInterval:(NSTimeInterval)playTimeInterval {
    _playTimeInterval = playTimeInterval;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 游戏时长间隔更新为: %.0f秒", playTimeInterval];
    
    // 如果定时器正在运行，重新启动
    if (self.playTimeTimer && self.sceneManagerEnabled) {
        [self resetPlayTimeTimer];
    }
}

- (void)setLevelWaitInterval:(NSTimeInterval)levelWaitInterval {
    _levelWaitInterval = levelWaitInterval;
    [IMLogUtils info:IMLogTagAd format:@"📱 [SceneManager] 关卡等待间隔更新为: %.0f秒", levelWaitInterval];
    
    // 如果定时器正在运行，重新启动
    if (self.levelWaitTimer && self.sceneManagerEnabled) {
        [self resetLevelWaitTimer];
    }
}

@end